//
//  ZYModifyUserInfoViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/6/13.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYModifyUserInfoViewModel.h"
#import "AFNetWorkUtils.h"
#import "ZYUser.h"
#import "ZYProblem.h"

@implementation ZYModifyUserInfoViewModel


-(RACCommand *)nicknameModifyCommand{
    if(!_nicknameModifyCommand){
        _nicknameModifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                //校验昵称
                if(NULLString(self.nickname)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_USERNAME_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                [self doModifyUserInfo:subscriber withType:ZYModifyUserInfoTypeNickname];
                return nil;
            }];
        }];
    }
    return _nicknameModifyCommand;
}

-(RACCommand *)phoneModifyCommand{
    if(!_phoneModifyCommand){
        _phoneModifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                //验证手机号和code
                if(NULLString(self.phone)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PHONE_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                if(NULLString(self.code)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_CODE_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                if(![ZYBasicHelper validateMobile:self.phone]){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PHONE]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                [self doModifyUserInfo:subscriber withType:ZYModifyUserInfoTypePhone];
                return nil;
            }];
        }];
    }
    return _phoneModifyCommand;
}

-(RACCommand *)emailModifyCommand{
    if(!_emailModifyCommand){
        _emailModifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                //验证邮箱和code
                if(NULLString(self.email)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_EMAIL_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                if(NULLString(self.code)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_CODE_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                if(![ZYBasicHelper validateEmail:self.email]){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_EMAIL]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                [self doModifyUserInfo:subscriber withType:ZYModifyUserInfoTypeEmail];
                return nil;
            }];
        }];
    }
    return _emailModifyCommand;
}

-(RACCommand *)problemModifyCommand{
    if(!_problemModifyCommand){
        _problemModifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                //校验答案
                if(NULLString(self.answer)){
                    [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PROBLEM_EMPTY]]];
                    [subscriber sendCompleted];
                    return nil;
                }
                [self doModifyUserInfo:subscriber withType:ZYModifyUserInfoTypeProblem];
                return nil;
            }];
        }];
    }
    return _problemModifyCommand;
}

-(RACCommand *)passwordModifyCommand{
    if(!_passwordModifyCommand){
        _passwordModifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                //校验密码
                BOOL success = [self checkPasswordData:subscriber];
                if(!success){
                    return nil;
                }
                [self doModifyUserInfo:subscriber withType:ZYModifyUserInfoTypePassword];
                return nil;
            }];
        }];
    }
    return _passwordModifyCommand;
}


/**
 校验密码
 @param subscriber subscriber
 @return 是否成功
 */
-(BOOL)checkPasswordData:(id<RACSubscriber>)subscriber{
    if(NULLString(self.password)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(NULLString(self.oldPassword)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_OLD_PASSWORD_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(![self.password isEqualToString:self.rePassword]){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_INCONSISTENT_PASSWORD]]];
        [subscriber sendCompleted];
        return NO;
    }
    return YES;
}

/**
 执行修改操作
 @param subscriber subscriber
 @param type 类型ZYModifyUserInfoType
 */
-(void)doModifyUserInfo:(id<RACSubscriber>)subscriber withType:(ZYModifyUserInfoType)type{
    NSDictionary *params;
    NSString *url = @"";
    NSString *token = [ZYConfig loginToken];
    ZYUser *user = [ZYConfig userInfo];
    int languageType = 0;
    switch (type) {
        case ZYModifyUserInfoTypeNickname:
            params = @{@"userName":self.nickname,@"ssid":token};
            url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_MODIFY_USERNAME_URL];
            break;
        case ZYModifyUserInfoTypePhone:
            params = @{@"phone":self.phone,@"code":self.code,@"ssid":token};
            url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_MODIFY_PHONE_URL];
            break;
        case ZYModifyUserInfoTypeEmail:
           params = @{@"email":self.email,@"code":self.code,@"ssid":token};
            url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_MODIFY_EMAIL_URL];
            break;
        case ZYModifyUserInfoTypeProblem:
            if([[[ZYChangeLanguage sharedZYChangeLanguage] userLanguage] hasPrefix:@"en"]){
                languageType = 1;
            }else{
                languageType = 0;
            }
            params = @{@"code":self.problemId,@"answer":self.answer,@"uid":[NSString stringWithFormat:@"%ld",user.userId],@"type":[NSNumber numberWithInt:languageType],@"ssid":token};
            url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_MODIFY_PROBLEM_URL];
            break;
        case ZYModifyUserInfoTypePassword:
            params = @{@"oldPwd":self.oldPassword,@"newPwd":self.password,@"ssid":token};
            url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_MODIFY_PASSWORD_URL];
            break;
            
        default:
            break;
    }
    [[AFNetWorkUtils racPOSTWithURL:url params:params] subscribeNext:^(id x) {
        //保存用户信息
        NSDictionary *responseObject = x;
        ZYUser *user = [ZYUser modelWithJSON:[responseObject objectForKey:@"result"]];
        if(type != ZYModifyUserInfoTypeProblem){
            [ZYConfig saveUserInfo:user];
        }
        RACTuple *tuple = [RACTuple tupleWithObjects:[NSNumber numberWithBool:YES], nil];
        [subscriber sendNext:tuple];
        [subscriber sendCompleted];
    } error:^(NSError *error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];
}

-(RACCommand *)problemDataCommand{
    if(!_problemDataCommand){
        _problemDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [[AFNetWorkUtils racGETWithURL:[NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_GET_QUESTION_LIST_URL]] map:^id(id value) {
                NSDictionary *data = value;
                NSDictionary *result = [data objectForKey:@"result"];
                NSArray *row = [result objectForKey:@"rows"];
                if(!row){
                    return [NSMutableArray array];
                }
                return [NSArray modelArrayWithClass:[ZYProblem class] json:row];
            }];
        }];

    }
    return _problemDataCommand;
}

@end
